//
//  UIImage+resize.m
//  CoderLT
//
//  Created by CoderLT on 2017/5/27.
//  Copyright © 2017年 CoderLT. All rights reserved.
//

#import "UIImage+ATKit.h"

@implementation UIImage (resize)
- (instancetype)resizeBySizeRatio:(CGSize)size {
    CGSize newSize = self.size;
    if (newSize.width/newSize.height > size.width/size.height) {
        newSize.height = newSize.width * size.height / size.width;
    }
    else {
        newSize.width = newSize.height * size.width / size.height;
    }
    return [self resizeToSize:newSize];
}

- (instancetype)resizeToSize:(CGSize)size {
    return [self resizeToSize:size
                contentInsets:UIEdgeInsetsMake(size.height * 0.2f, size.width * 0.2f,
                                               size.height * 0.2f, size.width * 0.2f)
              backgroundColor:[UIColor colorWithWhite:0xEE/255.0f alpha:1.0f]];
}

- (instancetype)resizeToSize:(CGSize)size contentInsets:(UIEdgeInsets)insets backgroundColor:(UIColor *)color {
    if (size.width == 0 || size.height == 0) {
        return nil;
    }
    
    BOOL opaque = color && (CGColorGetAlpha(color.CGColor) > 0.999f);
    // Create a graphics image context
    UIGraphicsBeginImageContextWithOptions(size, opaque, self.scale);
    // set up background color
    if (color) {
        [color set];
        UIRectFill(CGRectMake(0, 0, size.width, size.height));
    }
    // Tell the old image to draw in this new context, with the desired new size
    CGRect rect;
    rect.origin.x = insets.left;
    rect.origin.y = insets.top;
    rect.size.width = size.width - insets.left - insets.right;
    rect.size.height = size.height - insets.top - insets.bottom;
    if (self.size.width/self.size.height > rect.size.width/rect.size.height) {
        rect.size.height = rect.size.width * self.size.height / self.size.width;
        rect.origin.y = (size.height + insets.top - insets.bottom - rect.size.height) / 2;
    }
    else {
        rect.size.width = rect.size.height * self.size.width / self.size.height;
        rect.origin.x = (size.width + insets.left - insets.right - rect.size.width) / 2;
    }
    [self drawInRect:rect];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

- (instancetype)imageCircle {
    CGFloat minSize = MIN(self.size.width, self.size.height);
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(minSize, minSize), NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, minSize, minSize);
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -rect.size.height);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:minSize/2];
    [path closePath];
    
    CGContextSaveGState(context);
    [path addClip];
    CGContextDrawImage(context, CGRectMake((minSize - self.size.width)/2, (minSize - self.size.height)/2, self.size.width, self.size.height), self.CGImage);
    CGContextRestoreGState(context);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)launchImage {
    CGFloat height = MAX([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict) {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
        if (imageSize.height == height) {
            return [UIImage imageNamed:dict[@"UILaunchImageName"]];
        }
    }
    return nil;
}

- (CVPixelBufferRef)pixelBuffer {
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                             @{}, kCVPixelBufferIOSurfacePropertiesKey,
                             nil];
    CVPixelBufferRef pxbuffer = NULL;
    CGFloat frameWidth = CGImageGetWidth([self CGImage]);
    CGFloat frameHeight = CGImageGetHeight([self CGImage]);
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault,
                                          frameWidth,
                                          frameHeight,
                                          kCVPixelFormatType_32BGRA,
                                          (__bridge CFDictionaryRef) options,
                                          &pxbuffer);
    if (status != kCVReturnSuccess) {
        return NULL;
    }
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata,
                                                 frameWidth,
                                                 frameHeight,
                                                 8,
                                                 CVPixelBufferGetBytesPerRow(pxbuffer),
                                                 rgbColorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    CGContextConcatCTM(context, CGAffineTransformIdentity);
    CGContextDrawImage(context, CGRectMake(0,
                                           0,
                                           frameWidth,
                                           frameHeight),
                       [self CGImage]);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    return pxbuffer;
}
@end
